//let shots=0
let appFile
let appIconFile
let appShotFile
let uploading_progress_percentage
let uploading_progress_inner
let uploading_mask
let alter_user_info
let user_pw_input
let user_name_input
let user_avatar_file
let user_avatar_view
let alteredAvatarView=false
var e = document.createEvent('MouseEvents')
e.initEvent('click', true, true)
let change_app_statue
let notice_p
let date=new Date()
let change_app_category

window.onload = function () {
    init()
    adminInit()
}
function init() {
    Array.from(document.getElementsByClassName('side_menu_item')).forEach(sideMenuItem => {
        sideMenuItem.addEventListener('click', function () {
            changeMenu(sideMenuItem.getAttribute('itemid'))
        })
    })
    document.getElementById('uploading_btn').addEventListener('click', uploading)
    document.getElementById('app_icon').addEventListener('change', changeAppIcon)
    document.getElementById('app_shot').addEventListener('change', changeAppShot)
    uploading_progress_percentage = document.getElementById('uploading_progress_percentage')
    uploading_progress_inner = document.getElementById('uploading_progress_inner')
    uploading_mask = document.getElementById('uploading_mask')
    document.getElementById('app_file').addEventListener('change', function () {
        appFile = document.getElementById('app_file').files[0]
    })
    alter_user_info=document.getElementById('alter_user_info').addEventListener('click',alterUserInfo)
    user_pw_input=document.getElementById('user_pw_input')
    user_name_input=document.getElementById('use_name_input')
    user_avatar_file=document.getElementById('user_avatar_file')
    user_avatar_file.addEventListener('change',alterUserAvatarFile)
    user_avatar_view=document.getElementById('user_avatar_view')
    user_avatar_view.addEventListener('click',user_avatar_viewListener)
    change_app_statue=document.getElementsByClassName('change_app_statue')
    change_app_category=document.getElementsByClassName('change_app_category')
    dispatchEventForSelect()
    notice_p=document.getElementById('notice_p')
}
function changeMenu(itemid) {
    Array.from(document.getElementsByClassName('area')).forEach(el => {
        el.style.display = 'none'
    })
    document.getElementsByClassName('area')[itemid].style.display = 'block'
}
function changeAppIcon() {
    appIconFile = document.getElementById('app_icon').files[0]
    let urlData = window.URL.createObjectURL(appIconFile)
    document.getElementById('app_icon_view').setAttribute('src', urlData)
}
function changeAppShot() {
    appShotFile = document.getElementById('app_shot').files
    //shots=document.getElementById('app_shot').files.length
    document.getElementById('app_shot_img').innerHTML = ''
    Array.from(appShotFile).forEach(shotImgFile => {
        let urlData = window.URL.createObjectURL(shotImgFile)
        let imgEL = document.createElement('img')
        let liEL = document.createElement('li')
        liEL.appendChild(imgEL)
        imgEL.setAttribute('src', urlData)
        document.getElementById('app_shot_img').appendChild(liEL)
    })
}
function uploading() {
    uploading_mask.style.display = 'flex'
    let fordata = new FormData()
    fordata.append('app_name', document.getElementById('app_name').value)
    fordata.append('app_desc', document.getElementById('app_desc').value)
    fordata.append('app_file', appFile)
    fordata.append('app_icon', appIconFile)
    fordata.append('app_category', document.getElementById('app_category').value)
    let i = 0
    Array.from(appShotFile).forEach(shotImgFile => {
        fordata.append('appShot_' + i, shotImgFile)
        i = i + 1
    })
    fordata.append('shots', i)

    axios({
        method: 'post',
        url: '/upload/app',
        data: fordata,
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: function (progressEvent) {
            let currentPercent = Math.floor(progressEvent.loaded / progressEvent.total * 100)
            uploading_progress_inner.style.width = currentPercent + '%'
            uploading_progress_percentage.textContent = '正在上传中......' + currentPercent + '%'
        }
    }).then(resp => {
        if (resp.data.upload_result) {
            alert('上传成功')
            location.reload()
        } else {
            alert('上传失败')
        }
    }).catch(err=>{
        alert('上传失败：'+err)
    })
}
function user_avatar_viewListener(){
    if(document.getElementById('alter_user_info').textContent=='修改')return
    user_avatar_file.dispatchEvent(e)
}
function alterUserAvatarFile(){
    if(user_avatar_file.files[0]==null){
        alteredAvatarView=false
        return
    }
    alteredAvatarView=true
    let userAvatarURL=window.URL.createObjectURL(user_avatar_file.files[0])
    user_avatar_view.setAttribute('src',userAvatarURL)
}
function alterUserInfo(){
    let btnText=document.getElementById('alter_user_info').textContent
    if(btnText=='修改'){
        user_pw_input.attributes.removeNamedItem('disabled')
        user_name_input.attributes.removeNamedItem('disabled')
        document.getElementById('alter_user_info').textContent='保存'
        return
    }else{
        user_pw_input.setAttribute('disabled','true')
        user_name_input.setAttribute('disabled','true')
        document.getElementById('alter_user_info').textContent='修改'
    }
    let fordata = new FormData()
    fordata.append('user_name',user_name_input.value)
    fordata.append('user_pw',user_pw_input.value)
    if(alteredAvatarView)
        fordata.append('user_avatar',user_avatar_file.files[0])
    axios({
        method: 'post',
        url: '/user/alter_user_info',
        data: fordata,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }).then(resp => {
        if (resp.data.result) {
            alert('修改成功')
            location.reload()
        } else {
            alert('修改失败')
        }
    }).catch(err=>{
        alert('修改失败：'+err)
    })

}
function dispatchEventForSelect(){
    Array.from(change_app_statue).forEach(el=>{
        el.addEventListener('change',function(){updateAppStatue(el)})
    })
    Array.from(change_app_category).forEach(el=>{
        el.addEventListener('change',function(){updateAppCategory(el)})
    })
}
function updateAppCategory(el){
    let value=el.value
    if(value.startsWith('app'))return
    simpleUpdateAjax('/update/update_app_category?app_name='+el.getAttribute('appname')+
        '&app_category='+value,'修改 '+el.getAttribute('appname')+' 分类为 '+value)
}
function updateAppStatue(el){
    let value=el.value
    if(value.startsWith('app'))return
    simpleUpdateAjax('/update/update_app_statue?app_name='+el.getAttribute('appname')+
        '&app_statue='+value,'修改 '+el.getAttribute('appname')+' 状态为 '+value,{
            onCompleted:function(data){
                if(value=='删除'){
                    location.reload()
                }
            }
        })
}
function simpleUpdateAjax(api,notification,recall){
    fetch(api,{method:'GET'}).then(resp=>{
        resp.json().then(data=>{
            if(data.result){
                notice_p.textContent=date+': '+notification+' 成功'
                notice_p.style.color='green'
            }else{
                notice_p.textContent=date+': '+notification+' 失败'
                notice_p.style.color='red'
            }
            if(recall!=null){
                recall.onCompleted(data)
            }
        })
    }).catch(err=>{
        notice_p.textContent=date+': '+notification+' 失败, err='+err
        notice_p.style.color='red'
    })
}